#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>

class SafeThread {
public:
    SafeThread() : m_running(false) {}

    ~SafeThread() {
        Stop();
    }

    void Start() {
        if (m_running) return;

        m_running = true;
        m_thread = std::thread(&SafeThread::Run, this);
    }

    void Stop() {
        if (!m_running) return;

        {
            std::lock_guard<std::mutex> lock(m_mutex);
            m_running = false; // 设置标志位
        }
        m_cv.notify_all(); // 通知线程退出

        if (m_thread.joinable()) {
            m_thread.join();
        }
    }

    void Pause() {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_paused = true;
    }

    void Resume() {
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            m_paused = false;
        }
        m_cv.notify_all(); // 通知线程恢复
    }

private:
    void Run() {
        while (m_running) {
            std::unique_lock<std::mutex> lock(m_mutex);

            // 如果线程被暂停，等待恢复
            m_cv.wait(lock, [this]() { return !m_paused || !m_running; });

            if (!m_running) break;

            // 模拟线程工作
            std::cout << "Thread is running..." << std::endl;
            lock.unlock(); // 解锁，允许其他操作
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        std::cout << "Thread is exiting..." << std::endl;
    }

    std::thread m_thread;
    std::atomic<bool> m_running;
    std::atomic<bool> m_paused{false};
    std::mutex m_mutex;
    std::condition_variable m_cv;
};

int main() {
    SafeThread myThread;

    myThread.Start(); // 启动线程

    std::this_thread::sleep_for(std::chrono::seconds(1)); // 主线程等待 1 秒
    myThread.Pause(); // 暂停线程

    std::this_thread::sleep_for(std::chrono::seconds(1)); // 主线程等待 1 秒
    myThread.Resume(); // 恢复线程

    std::this_thread::sleep_for(std::chrono::seconds(1)); // 主线程等待 1 秒
    myThread.Stop(); // 停止线程

    return 0;
}